<?php
/**
 * Description: 统计相关
 * User: wh
 * Date: 2017-08-28
 * Time: 15:19
 */

namespace app\wxbackend\controller;

use app\wxbackend\controller\Wx\WxSession;
use app\wxbackend\model\BillManager;
use app\wxbackend\model\Building;
use app\wxbackend\model\Member;
use think\Controller;

class StatisticsController extends Controller
{
    /**
     * 获取物业，水电公司，运营方或托管业主对应的楼宇列表
     * @date   2017-06-22
     * @author wuhao
     *
     * @param Building $buildModel  楼宇模型
     * @param int      $dtype       用户类型
     * @param int      $mid         用户id
     * @return array
     */
    private function _getBuilding(Building $buildModel, $dtype, $mid)
    {
        if ($dtype == 1) {//业主
            $where = ['mid' => $mid, 'is_delete' => 0];
            $buildingId = $buildModel->getHouseList($where, 'building_id');
            if ($buildingId) {
                $idArr = array_unique(array_column($buildingId, 'building_id'));
                $res = $buildModel->getBuildingList(['id' => ['in', $idArr]], 'id, name');
            } else {
                $res = [];
            }
        } else {
            if ($dtype == 5) {//物业
                $where = ['property_id' => $mid, 'is_delete' => 0];
            } elseif ($dtype == 6) {//水电
                $where = ['hydropower_id' => $mid, 'is_delete' => 0];
            } elseif ($dtype == 3 || $dtype == 4) {//运营方或托管
                $where = ['mid' => $mid, 'is_delete' => 0];
            } elseif ($dtype == 0) {
                $where = [];
            }
            $res = $buildModel->getBuildingList($where, 'id, name');
        }

        return $res;
    }
    /**
     * 房源出租情况的统计(饼状图)
     * @date   2017-6-22
     * @author wuhao
     *
     * @return json
     */
    public function houseStatistics()
    {
        $openid = I('openid', '', 'strval');
        //$openid = 'o2-PovnAE_kYfb_Xiobw4lhgM7k4';
        if (!$openid) {
            $this->apiReturn(400, [], '未定义openid');
        }
        WxSession::setSession($openid);
        $buildModel   = new Building();
        //$memberModel = new Member();
        //$leaseModel   = new Lease();
        $rent = $unRent = $total = [];
        //获取用户基本信息
        //$memberInfo = $memberModel->getMemberByOpenid($openid);
        //获取对应的楼宇信息
        if (!session('mid')) {
            $this->apiReturn(400, [], '未绑定平台账号');
        }
        $buildingInfo = $this->_getBuilding($buildModel, session('pdtype'), session('pmid'));
        if (!$buildingInfo) {
            $this->apiReturn(400, [], '无相关房源');
        }
        $buildIdArr = array_column($buildingInfo, 'id');
        //获取对应的房源
        $houseList  = $buildModel->getHouseList(['building_id' => ['in', $buildIdArr], 'is_delete' => 0], 'building_id, mid, house_number, status');
        if (!$houseList) {
            $this->apiReturn(400, [], '无相关房源');
        }

        $sumInfo = [];
        $countRent = $countUnRent = 0;
        foreach ($houseList as $h) {
            if (!isset($sumInfo[$h['building_id']])) {
                $sumInfo[$h['building_id']]['rent'] = 0;
                $sumInfo[$h['building_id']]['un_rent'] = 0;
                $sumInfo[$h['building_id']]['sum'] = 0;
            }

            $sumInfo[$h['building_id']]['sum']++;
            if ($h['status'] == 1) {//已出租
                $sumInfo[$h['building_id']]['rent']++;
                $countRent++;
            } else {//未出租
                $sumInfo[$h['building_id']]['un_rent']++;
                $countUnRent++;
            }
        }

        foreach ($sumInfo as $k => $s) {
            foreach ($buildingInfo as $b) {
                if ($k == $b['id']) {
                    $sumInfo[$k]['name'] = $b['name'];
                    break;
                }
            }
        }

        foreach ($sumInfo as $key => $sum) {//取出对应的出租和未出租情况
            $tmpRent = [
                'building_id' => $key,
                'name'        => $sum['name'],
                'sum'         => $sum['rent'],
            ];
            $tmpUnRent = [
                'building_id' => $key,
                'name'        => $sum['name'],
                'sum'         => $sum['un_rent'],
            ];
            $tmpTotal = [
                'building_id' => $key,
                'name'        => $sum['name'],
                'sum'         => $sum['sum'],
            ];
            $rent[] = $tmpRent;
            $unRent[] = $tmpUnRent;
            $total[] = $tmpTotal;
            unset($tmpRent, $tmpUnRent, $tmpTotal);
        }

        $data  = [
            'sum_rent'    => $countRent,
            'sum_un_rent' => $countUnRent,
            'rent'        => $rent,
            'un_rent'     => $unRent,
            'total'       => $total
        ];
        $this->apiReturn(200, $data, '');
    }


    /**
     * 获取这个收费周期的收入情况（柱状图）
     * @date   2017-6-22
     * @author wuhao
     *
     * @return json
     */
    public function moneyStatistics()
    {
        $openid = I('openid', '', 'strval');
        //$openid = 'o2-PovnAE_kYfb_Xiobw4lhgM7k4';
        if (!$openid) {
            $this->apiReturn(400, [], '未定义openid');
        }
        WxSession::setSession($openid);
        if (!session('mid')) {
            $this->apiReturn(400, [], '未绑定平台账号');
        }

        $buildModel   = new Building();
        $billModel    = new BillManager();
        //获取对应的楼宇信息
        //var_dump($_SESSION);die;
        $buildingInfo = $this->_getBuilding($buildModel, session('pdtype'), session('pmid'));
        if (!$buildingInfo) {
            $this->apiReturn(400, [], '无相关房源');
        }
        $buildIdArr = array_column($buildingInfo, 'id');
        $data = [];
        foreach ($buildingInfo as $b) {
            $data[]  = ['building_id' => $b['id'], 'name'=> $b['name'], 'pay_money' => 0, 'pay_count' =>0, 'un_pay_money' =>0, 'un_pay_count'=>0];
        }

        //获取本周期的账单
        $payBill = $billModel->getPayBillList(['owner_id'=>session('pmid'), 'bill_time'=> date('Ym'), 'building_id'=>['in', $buildIdArr], 'is_delete'=>0],
            'ordernum, building_id, begin_cycle, end_cycle, money, status');
        if (!$payBill) {
            $this->apiReturn(400, [], '无相关账单');
        }
        $billSum = [];
        foreach ($payBill as $p) {
            if (!isset($billSum[$p['ordernum']])) {
                $billSum[$p['ordernum']]['building_id'] = $p['building_id'];
                $billSum[$p['ordernum']]['money']       = 0;
                $billSum[$p['ordernum']]['status']      = $p['status'];
            }

            $billSum[$p['ordernum']]['money']+= $p['money'];
        }

        foreach ($billSum as $bill) {
            foreach ($data as $k =>  $d) {
                if ($d['building_id'] == $bill['building_id']) {
                    if ($bill['status'] == 0) {//未支付
                        $data[$k]['un_pay_money'] += $bill['money'];
                        $data[$k]['un_pay_count'] ++;
                    } else {
                        $data[$k]['pay_money'] += $bill['money'];
                        $data[$k]['pay_count'] ++;
                    }

                }
            }
        }
        $sum = 0;
        foreach ($data as $a => $b) {
            if ($b['pay_money'] == 0 && $b['un_pay_money'] == 0) {//去除空值
                unset($data[$a]);
            } else {
                //转化为元
                $data[$a]['pay_money']    = yuan($b['pay_money']);
                $sum += yuan($b['pay_money']);
                $data[$a]['un_pay_money'] = yuan($b['un_pay_money']);
            }
        }
        $data = array_merge($data);
        $res = [
            'list' => $data,
            'sum'  => $sum,
         ];

        $this->apiReturn(200, $res, '');
    }
}